package com.wzy.server.service.impl;

import com.wzy.server.pojo.Admin;
import com.wzy.server.pojo.Menu;
import com.wzy.server.mapper.MenuMapper;
import com.wzy.server.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.server.util.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wzy
 * @since 2021-04-30
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate redisTemplate;

//    根据用户id查询菜单列表
    @Override
    public List<Menu> getMenusByAdminId() {
//        System.out.println(((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
        //                 调用公共方法                   查询id
        Integer adminId = AdminUtils.getCurrentAdmin().getId();
        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
//        从redis获取菜单数据
        List<Menu> menus = (List<Menu>) valueOperations.get("menu_" + adminId);
//        如果为空，去数据库获取
        if (CollectionUtils.isEmpty(menus)){
//                                    查询id
            menus = menuMapper.getMenusByAdminId(adminId);
//            将数据库设置到Redis中
            valueOperations.set("menu_" + adminId,menus);
        }
        return menus;
    }

    //    根据角色获取菜单列表
    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenusWithRole();
    }



//    查询所有菜单
    @Override
    public List<Menu> getAllMenus() {

        return menuMapper.getAllMenus();
    }

}
